package com.itheima.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.bean.Employee;
import com.itheima.common.R;
import com.itheima.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService emp;

    /**
     * 员工登入
     * @param employee
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Employee employee, HttpSession session) {

        Employee empAll = emp.findAll(employee);

        if (empAll == null) {

            return R.error("用户名或密码错误!");

        }

        if (empAll.getStatus() == 0) {

            return R.error("该账号已被禁用!");

        }

        session.setAttribute("Employee",empAll);

        return R.success(empAll);

    }

    /**
     * 员工退出登入
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpSession session) {

        session.removeAttribute("Employee");

        session.invalidate();

        return R.success("退出成功!");

    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @PostMapping
    public R addEmployee(@RequestBody Employee employee) {

        int row = emp.add(employee);

        if (row > 0) {

            return R.success("添加员工成功!");

        }

        return R.error("添加员工失败!");

    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R findPage(int page, int pageSize, String name) {

        try {
            IPage<Employee> empPage = emp.findPage(page, pageSize, name);

            return R.success(empPage);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败!");
        }

    }

    /**
     * 修改状态和修改员工
     * @param employee
     * @return
     */
    @PutMapping
    public R updateStatus(@RequestBody Employee employee) {

        int row = emp.updateStatus(employee);

        if (row > 0) {

            return R.success("修改状态成功!");

        }

        return R.error("修改状态失败!");

    }

    /**
     * 通过id查找员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R findById(@PathVariable long id) {

        Employee employee = emp.findById(id);

        return R.success(employee);

    }
}
